import modelExtend from 'dva-model-extend'
import {lwjPageModel} from 'utils/model'
import pathToRegexp from 'path-to-regexp'
import {routerRedux} from 'dva/router'
import {query,create,onlineRecharge,accountRecharge,mine,accountBalance} from './service'

const commodityIds = [];
export default modelExtend(lwjPageModel, {
  namespace: 'cartcaluate',
  state: {
    activeTab: 1,
    addressList: [],
    isEdit: false,
    modalVisible: false,
    address: {},
    selectedShippingMethod: 'TAKE_BY_SELF',
    products: [],
    totalChannelPrice: 0,
    totalNumber: 0,
    accountBalance: 0,
    comment: '',
    storeList: [],
    selectedStoreId: null,
    paymentType: 'BALANCE',
    salesOrderId: null,
    cartList: []
  },
  subscriptions: {
    setup({dispatch, history}) {
      history.listen((location) => {
        const match = pathToRegexp('/salesmarket/cartcaluate/:index/:ids').exec(location.pathname);
        if(match){
          dispatch({
            type: 'reset',
            addressList: (location.state && location.state.item ? [location.state.item] : []),
            salesOrderId: (location.state && location.state.item ? location.state.item.id : null),
            selectedStoreId: (location.state ? location.state.salesDistributorId : null),
            cartList: (location.state && location.state.item ? location.state.cartList : [])
          })
          dispatch({
            type: 'setTabIndex',
            activeTab: parseInt(match[1])
          })
          if(match[1] != 2){
            let commodityIds = match[2].split("-");
            dispatch({
              type: 'query',
              ids: (location.state && location.state.item ? location.state.list : commodityIds),
              field: (location.state && location.state.item ? 'endGoods' : 'shopCartIds')
            })
            dispatch({
              type: 'accountBalance',
              id: (location.state ? location.state.salesDistributorId : null)
            })
          }
        }
      })
    }
  },
  effects: {
    //查询商品
    * query({ids,field}, {call, put, select}) {
      const {result: data} = yield call(query,{
        [field]: ids
      });
      yield put({
        type: 'setProducts',
        products: data.list,
        totalChannelPrice: data.totalChannelPrice,
        totalNumber: data.totalNumber
      });
    },
    //查询门店
    * mine({}, {call, put, select}) {
      const {list: data} = yield call(mine);
      yield put({
        type: 'setStoreList',
        storeList: data
      });
    },
    //去线上支付
    * queryOnlinePayment({queryParam}, { select, call, put }) {
      const newWindow = window.open();
      const dataLog = yield call(create, queryParam);
      if (dataLog.code === 0) {        
        const dataPath = yield call(onlineRecharge, {
          payMoney: queryParam.amountInPrice,
          showUrl: window.location.href.replace('/1/','/2/'),
          rechargeId: dataLog.result,
          paymentReceiptType: 'PLACE_ORDER'
        });
        if (dataPath.code === 0) {
          newWindow.location.href = dataPath.result
        }
        yield put({
          type: 'setTabIndex',
          activeTab: 2
        })
      }else{
        newWindow.close();
      }
    },
    //去余额支付
    * queryAccountPayment({queryParam}, { select, call, put }) {
      const dataPath = yield call(accountRecharge, queryParam);
      yield put({
        type: 'setTabIndex',
        activeTab: 2
      })
    },
    * accountBalance({id}, { select, call, put }) {
      const {result: data} = yield call(accountBalance, {
        id: id
      });
      yield put({
        type: 'setAccountBalance',
        accountBalance: data.overall
      })
    },
    * backOrderCart({}, { select, call, put }) {
      let selectedStoreId = yield select(({cartcaluate}) => cartcaluate.selectedStoreId);
      let salesOrderId = yield select(({cartcaluate}) => cartcaluate.salesOrderId);
      let addressList = yield select(({cartcaluate}) => cartcaluate.addressList);
      let address = (addressList && addressList.length > 0 ? addressList[0] : {});
      address.id = salesOrderId;
      let cartList = yield select(({cartcaluate}) => cartcaluate.cartList);
      yield put(routerRedux.push('/order/salesmarket',{cartList: cartList, item: address, salesDistributorId: selectedStoreId}));
    },
    * backSalesmarketCart({id}, { select, call, put }) {
      let selectedStoreId = yield select(({cartcaluate}) => cartcaluate.selectedStoreId);
      yield put(routerRedux.push(`/salesmarket/cartList?id=${selectedStoreId}`));
    }
  },

  reducers: {
    setTabIndex(state, {activeTab}) {
      return{
        ...state,
        activeTab
      }
    },
    setStoreList(state, {storeList}) {
      return{
        ...state,
        storeList
      }
    },
    setSelectedStoreId(state, {selectedStoreId}) {
      return{
        ...state,
        selectedStoreId
      }
    },
    setAccountBalance(state, {accountBalance}) {
      return{
        ...state,
        accountBalance
      }
    },
    //更新地址列表
    setAddressList(state, {addressList}) {
      return{
        ...state,
        addressList
      }
    },
    //弹窗切换
    showModal(state,{address, modalVisible}){
      return{
        ...state,
        modalVisible,
        address
      }
    },
    //关闭弹窗
    hideModal(state){
      return{
        ...state,
        modalVisible: false
      }
    },
    //新增地址成功
    saveAddressSuccess(state,{payload}){
      return{
        ...state,
        modalVisible:false
      }
    },
    //删除地址成功
    deleteAddressSuccess(state,{payload}){
      return{
        ...state
      }
    },
    //设置配送方式
    setShippingMethod(state, {id}){
      return{
        ...state,
        selectedShippingMethod: id
      }
    },
    //设置查询商品
    setProducts(state, {products, totalChannelPrice, totalNumber}) {
      console.log(products)
      console.log(totalChannelPrice)
      console.log(totalNumber)
      return{
        ...state,
        products,
        totalChannelPrice,
        totalNumber
      }
    },
    //选填备注
    setComment(state, {comment}) {
      return{
        ...state,
        comment
      }
    },
    //设置支付类型
    setPaymentType(state, {paymentType}) {
      return{
        ...state,
        paymentType
      }
    },
    reset(state, {addressList,selectedStoreId,salesOrderId, cartList}){
      return{
        activeTab: 1,
        addressList: addressList,
        isEdit: false,
        modalVisible: false,
        address: {},
        selectedShippingMethod: 'TAKE_BY_SELF',
        products: [],
        totalChannelPrice: 0,
        totalNumber: 0,
        accountBalance: 0,
        comment: '',
        storeList: [],
        accountBalance: null,
        paymentType: 'BALANCE',
        salesOrderId: (salesOrderId ? salesOrderId : null),
        selectedStoreId,
        cartList
      }
    }
  }
})
